<template>
  <el-menu
    default-active="2"
    class="el-menu-vertical-demo"
    @open="handleOpen"
    @close="handleClose"
  >
    <ForMenu :authMenuList="needShowRoute"></ForMenu>
  </el-menu>
</template>

<script setup lang="ts">
// 基于的 router.getRoutes() 方式
import { defineComponent } from 'vue'
import { RouteRecordRaw } from 'vue-router'
import { staticRoutes } from '@/router/staticRoutes'
import ForMenu from './ForMenu.vue'

function handleOpen(key: string) {}
function handleClose(key: string) {}

// 过滤路由配置 可以在pinia中实现动态路由添加
const needShowRoute = filterRoutesByPermission(staticRoutes)

function filterRoutesByPermission(routes: RouteRecordRaw[], userPermissions = ["admin"]) {
  // 深度遍历路由配置
  return routes.filter(route => {
    // 递归处理子路由
    if (route.children) {
      route.children = filterRoutesByPermission(route.children, userPermissions)
    }

    if (route.meta?.hidden as boolean) {
      return false; // hidden为true则直接过滤掉
    }

    // 检查路由权限配置
    const routePermissions = route.meta?.permission
    // 情况1：路由不需要任何权限
    if (!routePermissions) return true

    // 情况2：路由需要权限但用户没有权限 或者是本身就需要隐藏
    if (!Array.isArray(routePermissions)) return false

    // 情况3：路由需要权限且用户有相应权限
    return routePermissions.some(permission => userPermissions.includes(permission))
  })
}
// 组件显式命名 
defineComponent({
  name: 'RecursiveMenuComponent',
})

</script>